import { Component, OnInit } from '@angular/core';
import { Store } from '@ngxs/store';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Navigate } from '@ngxs/router-plugin';
import { RouterSelectors } from '../../../store/router';
import { SellerService } from '../seller.service';

@Component({
  selector: 'app-store-new',
  templateUrl: './store-new.component.html',
  styleUrls: ['./store-new.component.scss'],
})
export class StoreNewComponent implements OnInit {
  validateForm: FormGroup;

  constructor(
    private store: Store,
    private fb: FormBuilder,
    private service: SellerService,
  ) {
    this.validateForm = this.fb.group({
      id: [null, []],
      title: [null, [Validators.required]],
      description: [null, [Validators.required]],
      current: [false],
    });
  }

  ngOnInit(): void {
    const params = this.store.selectSnapshot(RouterSelectors.params);
    if (!!params.id) {
      this.service.storeDetails(params.id).subscribe(r => {
        this.validateForm.patchValue(r);
      });
    }

  }

  submitForm() {
    this.service.saveStores(this.validateForm.value).subscribe(() => {
      this.store.dispatch(new Navigate(['/seller/store']));
    });
  }
}
